<template>
  <div>
    <Form ref="formInline" :model="params" inline>
      <FormItem>
        <DatePicker type="daterange" placeholder="选择日期" style="width: 200px" v-model="params.date"
          @on-change="changeTime">
        </DatePicker>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="modal = true">上传报表</Button>
      </FormItem>
    </Form>
    <Table :columns="columns1" :data="data1">
      <template slot-scope="{row}" slot="path">
        <a @click="downExcel(row)">消费报表.xls</a>
      </template>
      <template slot-scope="{row}" slot="edit">
        <a @click="deleteOne(row)">删除</a>
      </template>
    </Table>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <Page :total="total" show-elevator show-sizer @on-change="changePage" @on-page-size-change="changePageSize" />
    </div>
    <Modal v-model="modal" title="上传数据" :mask-closable="false" @on-cancel="close">
      <Form ref="form" :model="params1">
        <FormItem label="报表日期：" required>
          <DatePicker type="daterange" placeholder="选择日期" style="width: 200px" v-model="params1.date"></DatePicker>
        </FormItem>
        <FormItem label="上传数据：">
          <Upload :headers="upHeaders" ref="upload" :action="url + '/v1/kq/index/report-upload'" name="file"
            :on-format-error="handleFormatError" :on-success="handleSuccess" :on-error="handleError"
            :format="['xlsx','xls']" :data="formatParams" :before-upload="handleUpload" show-upload-list>
            <Button type="primary" icon="ios-cloud-upload-outline">上传数据文件</Button>
          </Upload>
        </FormItem>
        <FormItem label="数据模板：">
          <a @click="downMB">消费数据模板.xls</a>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="close">取消</Button>
        <Button @click="submit" type="primary">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import util from "@/libs/util";
  import { getYKLIst, deleteYKLIst } from "@api/TApi/index.js"
  export default {
    computed: {
      formatParams() {
        return {
          start_time: this.params1.date[0] ? this.$Date(this.params1.date[0]).format("YYYY-MM-DD") : "",
          end_time: this.params1.date[1] ? this.$Date(this.params1.date[1]).format("YYYY-MM-DD") : "",
          type: 2
        }
      }
    },
    created() {
      this.url = process.env.VUE_APP_API
      this._getYKLIst()
      const token = util.cookies.get("token");
      let ProjectId = localStorage.getItem("currentProject");
      let MemberId = util.cookies.get("uuid");
      this.upHeaders.ProjectId = ProjectId
      this.upHeaders.Authorization = "Bearer " + token;
      this.upHeaders.MemberId = MemberId
    },
    data() {
      return {
        url: "",
        upHeaders: {
          ProjectId: "",
          Authorization: "",
          MemberId: "",
        },
        params1: {
          date: []
        },
        total: 0,
        modal: false,
        params: {
          date: [],
          page: 1,
          pageSize: 10,
        },
        columns1: [
          {
            title: '报表日期',
            key: 'report_time'
          },
          {
            title: '文件',
            slot: 'path'
          },
          {
            title: '上传日期',
            key: 'upload_time'
          },
          {
            title: '操作人',
            key: 'belong_member'
          },
          {
            title: '操作',
            slot: 'edit'
          }
        ],
        data1: [
          {
            name: 'John Brown',
            age: 18,
            address: 'New York No. 1 Lake Park',
            date: '2016-10-03'
          },
          {
            name: 'Jim Green',
            age: 24,
            address: 'London No. 1 Lake Park',
            date: '2016-10-01'
          },
          {
            name: 'Joe Black',
            age: 30,
            address: 'Sydney No. 1 Lake Park',
            date: '2016-10-02'
          },
          {
            name: 'Jon Snow',
            age: 26,
            address: 'Ottawa No. 2 Lake Park',
            date: '2016-10-04'
          }
        ],
        file: [],
        uploadFile: [],
      }
    },
    methods: {
      downMB() {
        window.open(this.url + '/excel/kq_report/template/消费查询模板.xlsx')
      },
      changePageSize(pageSize) {
        this.params.pageSize = pageSize
        this._getYKLIst()
      },
      changePage(page) {
        this.params.page = page
        this._getYKLIst()
      },
      changeTime() {
        this.params.page = 1
        this._getYKLIst()
      },
      downExcel(row) {
        window.open(this.url + row.report_path)
      },
      _getYKLIst() {
        let params = {
          page: this.params.page,
          pageSize: this.params.pageSize,
          type: 2,
          start_time: this.params.date[0] ? this.$Date(this.params.date[0]).format("YYYY-MM-DD") : "",
          end_time: this.params.date[1] ? this.$Date(this.params.date[1]).format("YYYY-MM-DD") : "",
        }
        getYKLIst(params).then(res => {
          this.total = res.total
          this.data1 = res.list
        })
      },
      close() {
        this.clearParams()
      },
      submit() {
        if (!this.params1.date[0] && !this.params1.date[1]) {
          this.$Message.error("请选择日期")
          return false
        }
        if (!this.uploadFile.length) {
          this.$Message.error("请选择文件")
          return false
        }
        for (let i = 0; i < this.uploadFile.length; i++) {
          let item = this.file[i]
          this.$refs.upload.post(item);
        }
      },
      handleUpload(file) {
        // 选择文件后 这里判断文件类型 保存文件 自定义一个keyid 值 方便后面删除操作
        let keyID = Math.random().toString().substr(2);
        file['keyID'] = keyID;
        // 保存文件到总展示文件数据里
        this.file.push(file);
        // 保存文件到需要上传的文件数组里
        this.uploadFile.push(file)
        // 返回 falsa 停止自动上传 我们需要手动上传
        return false;
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。'
        })
      },
      handleSuccess(res, file) {
        if (res.code === 200) {
          this.$Message.success("上传成功")
          this.clearParams()
          this._getYKLIst()
        }
      },
      clearParams() {
        this.modal = false
        this.$refs.upload.clearFiles()
        this.params1.date = []
      },
      handleError(error, file) {
        this.$Message.error("数据导入失败！")
      },
      deleteOne(row) {
        this.$Modal.confirm({
          title: "报表删除",
          content: "确定删除该报表吗？",
          onOk: () => {
            deleteYKLIst({ id: row.id }).then(res => {
              this.$Message.success("删除成功")
              this._getYKLIst()
            })
          }
        })
      }
    }
  }
</script>